<!-- 用户评价饼状图 -->
<template>
    <div class="pie-chart-container">
        <h2 class="chart-title">{{ title }}</h2>
        <span v-if="!data.length" class="no-comments-tip">暂无数据</span>
        <v-chart v-else class="pie-chart" :option="pieChartOption" autoresize />
    </div>
</template>

<script>
import { ref, onMounted, reactive, watch } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { PieChart } from 'echarts/charts';
import { TooltipComponent, LegendComponent } from 'echarts/components';
import VChart from 'vue-echarts';

use([
    CanvasRenderer,
    PieChart,
    TooltipComponent,
    LegendComponent
]);

export default {
    name: 'PieChartComponent',
    components: {
        VChart
    },
    props: {
        title: {
            type: String,
            default: '饼状图'
        },
        data: {
            type: Array,
            default: () => []
        }
    },
    setup(props) {
        const pieChartOption = reactive({
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                textStyle: {
                    color: '#94a3b8'
                }
            },
            series: [
                {
                    name: props.title,
                    type: 'pie',
                    radius: '50%',
                    center: ['50%', '50%'],
                    data: props.data,
                    label: {
                        color: '#fff',
                        formatter: '{b} ({d}%)'
                    }
                }
            ]
        });

        onMounted(() => {
            // 监听数据变化，更新图表 
            watch(() => props.data, (newData) => {
                pieChartOption.series[0].data = newData;
            }, { deep: true });
        });

        return {
            pieChartOption
        };
    }
};
</script>

<style scoped>
.pie-chart-container {
    padding: 20px;
    background-color: #1e293b;
    border-radius: 8px;
    margin-bottom: 20px;
}

.chart-title {
    color: #3b82f6;
    font-size: 20px;
    margin-bottom: 20px;
    font-weight: 600;
}

.pie-chart {
    height: 300px;
}

.no-comments-tip {
    color: white;
    font-size: 18px;
    text-align: center;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>